const paramUri = (a) => {
  const s = [];
  const rbracket = /\[\]$/;
  const isArray = function (obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  };
  const add = function (k, v) {
    const value = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
    s[s.length] = `${encodeURIComponent(k)}=${encodeURIComponent(value)}`;
  };
  const buildParams = function (prefix, obj) {
    let i;
    let len;
    let key;

    if (prefix) {
      if (isArray(obj)) {
        for (i = 0, len = obj.length; i < len; i += 1) {
          if (rbracket.test(prefix)) {
            add(prefix, obj[i]);
          } else {
            buildParams(`${prefix}[${typeof obj[i] === 'object' ? i : ''}]`, obj[i]);
          }
        }
      } else if (obj && String(obj) === '[object Object]') {
        for (key in obj) {
          if (obj[key]) {
            buildParams(`${prefix}[${key}]`, obj[key]);
          }
        }
      } else {
        add(prefix, obj);
      }
    } else if (isArray(obj)) {
      for (i = 0, len = obj.length; i < len; i += 1) {
        add(obj[i].name, obj[i].value);
      }
    } else {
      for (key in obj) {
        if (obj[key]) {
          buildParams(key, obj[key]);
        }
      }
    }
    return s;
  };

  return buildParams('', a).join('&').replace(/%20/g, '+');
};

export default paramUri;

